<!-- +----------------------------------------------------------------------
| 麦沃德科技赋能开发者，助力中小企业发展 
+----------------------------------------------------------------------
| Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
+----------------------------------------------------------------------
| 沃德代驾系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
+----------------------------------------------------------------------
| Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
+----------------------------------------------------------------------
| 地址选择 开发者: 麦沃德科技-半夏
+---------------------------------------------------------------------- -->

<template>
	<view class="container" :style="{'--theme-color': themeColor}">
		<view class="container-header flex">
			<view class="header-search flex-item flex align-items-center">
				<view class="search-point"></view>
				<input class="search-input flex-item" type="text" :placeholder="selectType == 1 ? '您从哪儿出发？' : '您要去哪儿？'" @input="handleSearch" />
			</view>
			<view class="header-choose flex-column flex-center" @click="chooseAddress()" v-if="selectType != 1">
				<image class="choose-icon" src="/static/address.png" mode="aspectFit"></image>
				<text class="choose-text">选地址</text>
			</view>
		</view>
		<block v-if="locationStatus == 1">
			<!-- 地址列表 -->
			<view class="container-list" v-if="addressList.length">
				<view class="list-item flex align-items-center" v-for="(item, index) in addressList" :key="index" @click="handleSelect(item)">
					<image class="item-icon" src="/static/address.png" mode="aspectFit"></image>
					<view class="item-info flex-item">
						<view class="info-name text-ellipsis">{{item.title}}</view>
						<view class="info-content text-ellipsis" v-if="item.address">{{item.address}}</view>
					</view>
				</view>
			</view>
			<!-- 历史记录 -->
			<view class="container-history" v-else-if="selectType != 1 && historyList.length">
				<view class="history-header flex flex-between-center">
					<view class="header-title">历史记录</view>
					<view class="header-btn flex align-items-center" @click="handleClear()">
						<image class="btn-icon" src="/static/clear.png" mode="aspectFit"></image>
						<text class="btn-text">清除记录</text>
					</view>
				</view>
				<uni-swipe-action class="history-list">
					<uni-swipe-action-item class="list-item" v-for="item in historyList" :key="item.id">
						<view class="item-box" @click="handleSelect(item)">
							<image class="box-icon" src="/static/address.png" mode="aspectFit"></image>
							<view class="box-info flex-item">
								<view class="info-name text-ellipsis">{{item.title}}</view>
								<view class="info-content text-ellipsis">{{item.address}}</view>
							</view>
						</view>
						<template v-slot:right>
							<view class="item-btn flex flex-center" @click="handleDelete(item.id)">删除</view>
						</template>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>
		</block>
		<view class="container-permission" v-else-if="locationStatus == 3">
			<view class="title">正在获取当前位置...</view>
		</view>
		<view class="container-permission" v-else>
			<view class="title">定位失败</view>
			<view class="content">位置获取失败，无法使用相关功能，<text class="text" @click="getAuthSetting()">点击重试</text></view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '@/common/qqmap-wx-jssdk.min.js'
	import { mapState } from "vuex"
	export default {
		data() {
			return {
				// 是否重新定位
				isResetLocation: false,
				// 定位状态 1.定位成功，2.定位失败，3.正在定位
				locationStatus: 3,
				// 当前定位
				currentLocation: {},
				// 搜索防抖延时器
				timer: null,
				// 地址列表
				addressList: [],
				// 历史记录
				historyList: [],
				// 地址选择类型 1-选择出发地，2-首页选择目的地，3-订单页选择目的地
				selectType: 1,
			}
		},
		computed: {
			...mapState({
				themeColor: state => state.app.themeColor,
				tencentMapKey: state => state.app.tencentMapKey,
			})
		},
		onLoad(option) {
			this.selectType = option.type
			uni.showLoading({
				title: "加载中",
				mask: true,
			})
			this.getAuthSetting(() => {
				uni.hideLoading()
			})
		},
		onShow() {
			if (this.isResetLocation) {
				this.isResetLocation = false
				this.getAuthSetting()
			}
		},
		onUnload() {
			if (this.timer) clearTimeout(this.timer)
		},
		methods: {
			// 获取位置权限
			async getAuthSetting(fn) {
				this.locationStatus = 3
				try {
					const permissionStatus = await this.$util.checkLocationPermission()
					if (permissionStatus == 1) {
						this.getAddressList(fn)
					} else {
						if (fn) fn()
						this.$util.setLocationPermission(permissionStatus, (result) => {
							if (result) {
								// #ifdef MP-WEIXIN
								this.getAddressList()
								// #endif
								// #ifdef APP
								this.isResetLocation = true
								// #endif
							} else {
								this.locationStatus = 2
							}
						})
					}
				} catch (error) {
					this.locationStatus = 2
					if (fn) fn()
					uni.showToast({
						title: error.message,
						icon: 'none',
						duration: 2000,
					})
				}
			},
			// 获取地址列表
			async getAddressList(fn) {
				if (this.selectType == 1) {
					var qqmapsdk = new QQMapWX({
						key: this.tencentMapKey
					})
					qqmapsdk.reverseGeocoder({
						get_poi: 1,
						success: (res) => {
							this.locationStatus = 1
							if (fn) fn()
							this.addressList = []
							this.currentLocation = {
								latitude: res.result.location.lat,
								longitude: res.result.location.lng,
							}
							res.result.pois.forEach((element) => {
								this.addressList.push({
									province: element.ad_info.province,
									city: element.ad_info.city,
									district: element.ad_info.district,
									title: element.title,
									address: element.address,
									latitude: element.location.lat,
									longitude: element.location.lng,
								})
							});
						},
						fail: () => {
							this.locationStatus = 2
							if (fn) fn()
							this.currentLocation = uni.getStorageSync("currentCity")
							uni.showToast({
								title: '位置获取失败',
								icon: 'none',
								duration: 2000,
							})
						},
					})
				} else {
					this.historyList = uni.getStorageSync("historyList") || []
					try {
						const locationData = await this.getLocation()
						this.locationStatus = 1
						this.currentLocation = locationData
						if (fn) fn()
					} catch (error) {
						this.locationStatus = 2
						if (fn) fn()
						this.currentLocation = uni.getStorageSync("currentCity")
						uni.showToast({
							title: '位置获取失败',
							icon: 'none',
							duration: 2000,
						})
					}
				}
			},
			// 获取当前经纬度
			getLocation() {
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						geocode: true,
						isHighAccuracy: true,
						success: (res) => {
							try {
								resolve({
									latitude: res.latitude,
									longitude: res.longitude,
									city: res.address.city,
								})
							} catch (error) {
								resolve({
									latitude: res.latitude,
									longitude: res.longitude,
								})
							}
						},
						fail: (error) => {
							reject(error);
						},
					})
				})
			},
			// 搜索地址
			handleSearch(e) {
				if (this.timer) clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.addressList = []
					if (!e.detail.value) return
					var qqmapsdk = new QQMapWX({
						key: this.tencentMapKey
					})
					qqmapsdk.getSuggestion({
						keyword: e.detail.value,
						location: this.currentLocation,
						success: (res) => {
							this.addressList = []
							res.data.forEach((element) => {
								this.addressList.push({
									province: element.province,
									city: element.city,
									district: element.district,
									title: element.title,
									address: element.address,
									latitude: element.location.lat,
									longitude: element.location.lng,
								})
							});
						},
						fail: () => {
							uni.showToast({
								title: '位置获取失败',
								icon: 'none',
								duration: 2000,
							})
						},
					})
				}, 500);
			},
			// 选择地址
			handleSelect(item) {
				if (this.selectType == 1) {
					let pages = getCurrentPages()
					let prevPage = pages[pages.length - 2]
					prevPage.$vm.selectAddress = {
						type: 1,
						province: item.province,
						city: item.city,
						district: item.district,
						title: item.title,
						latitude: item.latitude,
						longitude: item.longitude,
					}
					uni.navigateBack()
				} else {
					let historyData = uni.getStorageSync("historyList") || []
					if (historyData.some(obj => obj.address == item.address)) {
						const index = historyData.findIndex(el => el.address == item.address)
						if (index == -1 || historyData[index].address != item.address) return
						this.$delete(historyData, index)
					}
					historyData.unshift({
						id: new Date().getTime(),
						title: item.title,
						address: item.address,
						latitude: item.latitude,
						longitude: item.longitude,
					})
					uni.setStorageSync("historyList", historyData)
					let pages = getCurrentPages()
					let prevPage = pages[pages.length - 2]
					prevPage.$vm.selectAddress = {
						type: 2,
						title: item.title,
						latitude: item.latitude,
						longitude: item.longitude,
					}
					uni.navigateBack()
				}
			},
			// 清除历史记录
			handleClear() {
				uni.showModal({
					title: "系统提示",
					content: "确定要清除历史记录吗？",
					confirmColor: this.themeColor,
					success: (res) => {
						if (res.confirm) {
							uni.removeStorageSync("historyList")
							uni.showToast({
								icon: "success",
								title: "清除成功"
							})
							this.historyList = []
						}
					}
				})
			},
			// 删除历史记录
			handleDelete(id) {
				const index = this.historyList.findIndex((item) => item.id == id)
				this.$delete(this.historyList, index)
				uni.setStorageSync("historyList", this.historyList)
			},
			// 地图选址
			chooseAddress() {
				uni.chooseLocation({
					success: (res) => {
						this.handleSelect({
							title: res.name,
							address: res.address,
							latitude: res.latitude,
							longitude: res.longitude,
						})
					},
				});
			},
		},
	}
</script>

<style lang="scss">
	page {
		background: #FFF;
	}

	.container {
		padding: 24rpx 32rpx 32rpx;

		.container-header {
			.header-search {
				padding-left: 32rpx;
				border-radius: 16rpx;
				background: #F3F4F7;

				.search-point {
					width: 16rpx;
					height: 16rpx;
					border-radius: 50%;
					background: var(--theme-color);
				}

				.search-input {
					color: #8D929C;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;
					padding: 28rpx 32rpx 28rpx 16rpx;
				}
			}

			.header-choose {
				margin-left: 16rpx;
				padding: 0 20rpx;
				border-radius: 16rpx;
				background: #F3F4F7;

				.choose-icon {
					width: 32rpx;
					height: 32rpx;
				}

				.choose-text {
					margin-top: 8rpx;
					color: #242629;
					font-size: 24rpx;
					font-weight: 600;
					line-height: 34rpx;
				}
			}
		}

		.container-history {
			margin-top: 32rpx;

			.history-header {
				margin-bottom: 16rpx;

				.header-title {
					color: #333;
					text-align: center;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;
				}

				.header-btn {
					.btn-icon {
						width: 32rpx;
						height: 32rpx;
					}

					.btn-text {
						margin-left: 16rpx;
						color: #999;
						text-align: center;
						font-size: 28rpx;
						line-height: 40rpx;
					}
				}
			}

			.history-list {
				.list-item {
					border-top: 1px solid #EBEBEB;

					&:first-child {
						border-top: none;
					}

					.item-box {
						display: flex;
						align-items: center;

						.box-icon {
							width: 32rpx;
							height: 32rpx;
						}

						.box-info {
							padding: 32rpx 0;
							margin-left: 16rpx;

							.info-name {
								color: #242629;
								font-size: 28rpx;
								font-weight: 600;
								line-height: 40rpx;
							}

							.info-content {
								color: #8D929C;
								font-size: 24rpx;
								font-weight: 600;
								line-height: 34rpx;
							}
						}
					}

					.item-btn {
						margin-left: 16rpx;
						color: #ffffff;
						font-size: 28rpx;
						line-height: 40rpx;
						background: #FF2E2E;
						padding: 0 36rpx;
					}
				}
			}
		}

		.container-list {
			margin-top: 16rpx;

			.list-item {
				padding: 32rpx 0;
				border-top: 1px solid #EBEBEB;

				&:first-child {
					border-top: none;
				}

				.item-icon {
					width: 32rpx;
					height: 32rpx;
				}

				.item-info {
					margin-left: 16rpx;

					.info-name {
						color: #242629;
						font-size: 28rpx;
						font-weight: 600;
						line-height: 40rpx;
					}

					.info-content {
						color: #8D929C;
						font-size: 24rpx;
						font-weight: 600;
						line-height: 34rpx;
					}
				}
			}
		}

		.container-permission {
			margin-top: 32rpx;

			.title {
				color: #242629;
				font-size: 32rpx;
				font-weight: 600;
				line-height: 44rpx;
			}

			.content {
				margin-top: 16rpx;
				color: #8D929C;
				font-size: 28rpx;
				font-weight: 600;
				line-height: 36rpx;

				.text {
					color: var(--theme-color);
				}
			}
		}
	}
</style>